package tech.horgee.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import tech.horgee.common.IWrapper;
import tech.horgee.enums.MenuTypeEnum;
import tech.horgee.group.InsertGroup;
import tech.horgee.group.UpdateGroup;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * 菜单信息
 *
 * @author haojun
 * @since 2022-06-27
 */
@Getter
@Setter
@TableName("tab_menu")
public class Menu implements Serializable, IWrapper<Menu> {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @NotNull(groups = UpdateGroup.class)
    @TableId(value = "menu_id", type = IdType.AUTO)
    private Long menuId;

    /**
     * 菜单名称
     */
    @NotBlank(groups = InsertGroup.class)
    private String menuName;

    /**
     * 菜单权限
     */
    @NotBlank(groups = InsertGroup.class)
    private String permission;

    /**
     * 菜单类型
     */
    private MenuTypeEnum menuType;

    /**
     * 父菜单ID
     */
    private Long parentId;

    /**
     * 乐观锁
     */
    @NotNull(groups = UpdateGroup.class)
    @Version
    private Long version;

    /**
     * 逻辑删除
     */
    @TableLogic
    private Boolean deleted;

    /**
     * 创建时间
     */
    @TableField(updateStrategy = FieldStrategy.NEVER)
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField(updateStrategy = FieldStrategy.NEVER)
    private LocalDateTime updateTime;

    /**
     * 子节点
     */
    @TableField(exist = false)
    private List<Menu> children;

    /**
     * 枚举中文
     */
    public String getMenuTypeLabel() {
        return Optional.ofNullable(this.menuType).orElse(MenuTypeEnum.DIR).getLabel();
    }

    @Override
    public LambdaQueryWrapper<Menu> wrapper() {
        return new LambdaQueryWrapper<Menu>()
                .eq(Objects.nonNull(menuId), Menu::getMenuId, menuId)
                .like(Objects.nonNull(menuName), Menu::getMenuName, menuName)
                .eq(Objects.nonNull(permission), Menu::getPermission, permission)
                .eq(Objects.nonNull(menuType), Menu::getMenuType, menuType)
                .eq(Objects.nonNull(parentId), Menu::getParentId, parentId)
                .eq(Objects.nonNull(version), Menu::getVersion, version)
                .eq(Objects.nonNull(deleted), Menu::getDeleted, deleted)
                .eq(Objects.nonNull(createTime), Menu::getCreateTime, createTime)
                .eq(Objects.nonNull(updateTime), Menu::getUpdateTime, updateTime)
                .orderByAsc(Menu::getParentId)
                ;
    }
}
